package com.uam.core.dao.mysql;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.uam.core.entity.model.AircraftModel;
import com.uam.core.entity.model.PolygonV1;
import com.uam.core.entity.model.TaskModel;
import com.uam.core.entity.model.TaskQueryResult;
import lombok.extern.slf4j.Slf4j;
import org.locationtech.jts.geom.LineString;
import org.locationtech.jts.geom.Polygon;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author Administrator
 */
@Repository
@Slf4j
public class PolygonV1Dao {

	@Autowired
	private JdbcTemplate jdbcTemplate = null;


    public int  add(LineString polygon, AircraftModel aircraftModel, JSONObject jsonObject, TaskModel taskModel, JSONArray points){
    	try {
			long endTime = jsonObject.getLong("time");
			long endTime1 = taskModel.getStartTime().getTime() + endTime;
			Timestamp timestamp = new Timestamp(endTime1);
			String sql = "INSERT INTO `polygon_v1` ( `polygongeo`, `name`, `floor`, `start_time`, `end_time`, `create_time`, `task_id`,`points`,`safe_distance`,`avg_speed` ) " + " VALUES(  POLYGONFROMTEXT( '" + polygon.toText() + " '), '" + taskModel.getName() + "', " + jsonObject.getInteger("floor") + ", '" + taskModel.getStartTime() + "', '" + timestamp + "', NOW(), '" + taskModel.getId() + "', '" + JSON.toJSONString(points, SerializerFeature.DisableCircularReferenceDetect) + "'," + aircraftModel.getSafeDistance() + "," + aircraftModel.getSpeed() + ");";
//		log.info("sql：{}",sql);
			return jdbcTemplate.update(sql);
		}catch (Exception e){
			log.error("添加边界数据错误：",e);
    		return  0;
		}
	}

	public  List<PolygonV1> queryIntersects(LineString polygon, int floor, Timestamp startTime, long time) {
    	try {
			List<PolygonV1> data = this.jdbcTemplate.query(con -> {
				String sql = " SELECT " +
						"points, " +
						"task_id," +
						"safe_distance," +
						"avg_speed," +
						"ST_AsText (polygongeo) polygongeo," +
						"floor " +
						"FROM " +
						"(" +
						"SELECT " +
						"st_intersects ( geomFromText ('" + polygon.toText() + "' ), t.polygongeo ) intData, " +
						"polygongeo, " +
						"t.task_id, " +
						"t.floor, " +
						"t.safe_distance," +
						"t.avg_speed," +
						"points  " +
						"FROM " +
						"polygon_v1 t " +
						"WHERE  1=1 " +
						" and  floor = " + floor + "  " +
//					" AND start_time>= '"+startTime+"' " +
//			        " and end_time<='"+endTime+"'  " +
						") temp  " +
						"WHERE" +
						" temp.intData > 0 ";
//			log.info("查询相交cql：{}",sql);
				PreparedStatement ps = con.prepareStatement(sql);
				return ps;
			}, new RowMapper<PolygonV1>() {
				@Override
				public PolygonV1 mapRow(ResultSet rs, int rowNum) throws SQLException {
					PolygonV1 task = new PolygonV1(
							rs.getString("points"),
							rs.getLong("task_id"),
							rs.getInt("floor"),
							rs.getInt("safe_distance"),
							rs.getString("polygongeo"),
							rs.getDouble("avg_speed"));
					return task;
				}
			});
			return data;
		}catch (Exception e){
    		log.error("相交查询错误：",e);
    		return new ArrayList<>();
		}
	}

    public int delete(Long taskId) {
		return  jdbcTemplate.update("DELETE FROM  polygon_v1 where task_id="+taskId);
    }
}
